#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <string>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

enum{
    SOCK_ERROR = 1,
    BIND_ERRROR,
    USAGE_ERROR
};
const static int defaultfd = -1;

using func = std::function<void (int sockfd, const std::string message, const InetAddr addr)>;
using hander_message_t = std::function<void (int sockfd, const std::string message, const InetAddr who)>; // TODO

class UdpServer{
public:
    UdpServer(uint16_t port, func fun): _sockfd(defaultfd), _port(port), _isrunning(false), _func(fun){
    }

    void InitServer(){
        //第一个参数，是网络通信还是本地通信，第二个参数是TCP还是UDP

        //1.0 创建sockffd
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0) {
            LOG(FATAL,"socket create failed, %s, %d\n", strerror(errno), errno);
            exit(SOCK_ERROR);
        }
        LOG(INFO, "socket create success!,sockfd is %d\n", _sockfd);

        //2.0 填充sockfd_addr结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local));//初始化，赋值为0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);  
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;
        
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0){
            LOG(FATAL, "bind faild, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERRROR);
        }
        LOG(INFO, "bind success\n");
    }

    void Start(){
        while(1){
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr*)&peer, &len);
            InetAddr add(peer);
            if(n){
                message[n] = 0;
                std::cout << "[服务器收到来自" << add.Getip() << ": " << add.Getport() << "的消息为]：" << message << std::endl;
                
                //我自己的写的
                std::string response;
                std::getline(std::cin, response);
                _func(_sockfd, response, add);
            }
        }
        _isrunning = false;
    }
    ~UdpServer(){}
private:
    int _sockfd;
    //std::string _ip;
    uint16_t _port;
    bool _isrunning;
    func _func;
};